﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Models.Warning;
using Atmk.WaterMeter.MIS.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Atmk.WaterMeter.MIS.Controllers.Warning
{
    //[Produces("application/json")]
    //[Route("api/Warning")]
    /// <summary>
    /// 磁报警控制器
    /// </summary>
    [Authorize]
    public class WarningController : Controller
    {
        private readonly TokenHelper _tokenHelper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="tokenHelper"></param>
        public WarningController(TokenHelper tokenHelper)
        {
            _tokenHelper = tokenHelper;
        }
        /// <summary>
        ///  磁攻击报警
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="nodeType">节点类型 是否业主</param>
        /// <param name="id">节点id</param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/Warning/Magnetism")]
        public IActionResult Magnetism(int page, string nodeType,string id)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                //var userid = new Guid(token.payload.id);
                using (var context = ContextBuilder.Build())
                {
                    var pageSize = context.User.First(m => m.Id.ToString() == token.payload.id).PageLines;
                    var total_districts = context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var districts_ids = total_districts.Select(m1 => m1.Id.ToString());
                    var total_owners = context.Owner.Where(o => districts_ids.Contains(o.DistrictId)).ToList();
                    var owners_ids = total_owners.Select(m1 => m1.Id.ToString());
                    var total_meters = context.Meter.Where(m => m.MeterState == "建档" && owners_ids.Contains(m.OwnerId)).ToList();
                    var meterNumbers = total_meters.Select(m1 => m1.MeterNumber);

                    //var meterReads = context.MeterReadingRecords.Where(m => meterNumbers.Contains(m.Number) && m.MsgType == 4).ToList();
                    var meterReads = context.MeterReadingRecord.Where(m => meterNumbers.Contains(m.CtdeviceId)).ToList();
                    var warningModels = new List<WarningModel>();
                    foreach (var item in meterReads)
                    {
                        var temp_meter = total_meters.FirstOrDefault(m => m.MeterNumber == item.CtdeviceId);
                        var temp_owners = total_owners.FirstOrDefault(m => temp_meter == null ? false : m.Id.ToString() == temp_meter.OwnerId);
                        warningModels.Add(new WarningModel()
                        {
                            OwnerName = temp_owners?.Name,
                            //Mobile = temp_owners?.Mobile,
                            HouseNumber = temp_owners?.HouseNumber,
                            MeterNumber = temp_meter?.MeterNumber,
                            CurrentValue = item.Value.ToString(),
                            ReadTime = item.ReadTime.ToString(),
                            MsgType = ColumnType.msgtype(item.MsgType),
                            Voltage = Convert.ToDouble(item.Voltage),
                            ValueState = ValveStatic(item.ValveState)
                        });
                    }
                    var result_list = PaginatedList<WarningModel>.Create(warningModels, page, pageSize);
                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = warningModels.Count,
                            pageSize,
                            list = result_list
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }

        /// <summary>
        ///  消除磁攻击报警
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/Warning/ClearMagnetism")]
        public IActionResult ClearMagnetism(string MeterNumber)
        {
            try
            {
                return Ok(new { errcode = 0, msg = "ok" });
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }
        /// <summary>
        ///  低电压报警
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/Warning/LowVoltage")]
        public IActionResult LowVoltage(int page)
        {
            try
            {
                var token = _tokenHelper.GetTokenByHttpContext();
                var userid = new Guid(token.payload.id);
                using (var context = ContextBuilder.Build())
                {
                    var pageSize = context.User.First(m => m.Id.ToString() == token.payload.id).PageLines;
                    var total_districts = context.District.Where(m => m.ProjectId == token.payload.areaid).ToList();
                    var districts_ids = total_districts.Select(m1 => m1.Id.ToString());
                    var total_owners = context.Owner.Where(o => districts_ids.Contains(o.DistrictId)).ToList();
                    var owners_ids = total_owners.Select(m1 => m1.Id.ToString());
                    var total_meters = context.Meter.Where(m => m.MeterState == "建档" && owners_ids.Contains(m.OwnerId)).ToList();
                    var meterNumbers = total_meters.Select(m1 => m1.MeterNumber);

                    //var meterReads = context.MeterReadingRecords.Where(m => meterNumbers.Contains(m.Number) && m.MsgType == 4).ToList();
                    var meterReads = context.MeterReadingRecord.Where(m => meterNumbers.Contains(m.CtdeviceId)).ToList();
                    var warningModels = new List<WarningModel>();
                    foreach (var item in meterReads)
                    {
                        var temp_meter = total_meters.FirstOrDefault(m => m.MeterNumber == item.CtdeviceId);
                        var temp_owners = total_owners.FirstOrDefault(m => temp_meter == null ? false : m.Id.ToString() == temp_meter.OwnerId);
                        warningModels.Add(new WarningModel()
                        {
                            District = "片区",
                            OwnerName = temp_owners?.Name,
                            //Mobile = temp_owners?.Mobile,
                            HouseNumber = temp_owners?.HouseNumber,
                            MeterNumber = temp_meter?.MeterNumber,
                            CurrentValue = item.Value.ToString(),
                            ReadTime = item.ReadTime.ToString(),
                            MsgType = ColumnType.msgtype(item.MsgType),
                            Voltage = Convert.ToDouble(item.Voltage),
                            ValueState = ValveStatic(item.ValveState)
                        });
                    }
                    var result_list = PaginatedList<WarningModel>.Create(warningModels, page, pageSize);
                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            total = warningModels.Count,
                            pageSize,
                            list = result_list
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = 1, msg = ex.ToString() });
            }
        }
        //阀门状态
        public string ValveStatic(int? value)
        {
            switch (value)
            {
                case 0: return "关阀";
                case 1: return "开阀";
                case 2: return "异常";
                case 3: return "异常";
                default: return "";
            }
        }
    }
}